<script setup lang="ts">
import type { Page } from '@/types'
import { dateFormat, getFormatDictMap } from '@/util/dict'
import { onMounted, ref } from 'vue'
import { Search, Refresh } from '@/util/icons'
import Pagination from '@/components/Pagination.vue'
import type { UserTable } from '@/types/user'
import { icon } from '@/util/icons'
import { getAllUser, getUserBaseInfo } from '@/api/user'
import { ElMessage, type Sort } from 'element-plus'
import { UrlFormat } from '@/util/request'
import { getGroupUser, updateGroupUser } from './api'

const props = defineProps<{
  group: number
}>()
// 菜单名称
const page = ref<Page<UserTable>>({
  num: 1,
  size: 10,
  rows: [],
  count: 0
})
/* 获取对应的字典信息 */
const tableDict = ref<Map<string, string>>()
const statusDict = ref<Map<string, string>>()
const sexDict = ref<Map<string, string>>()

// 当前组有的用户ids
const users = ref<number[]>([])
// 用户信息缓存
const userMap = ref<Map<number, UserTable>>(new Map())
// 获取用户组的用户 以及用户信息
function getGroupUsers() {
  getGroupUser(props.group).then((d) => {
    users.value = d.data
    // 获取用户信息
    d.data.forEach((id) => {
      getUserBaseInfo(id).then((data) => {
        if (data.data) {
          userMap.value.set(data.data.uId!, data.data)
        }
      })
    })
  })
}

// 改变用户 是否在组
function changeUser(id: number, data?: UserTable) {
  const index = users.value.indexOf(id)
  if (index >= 0) {
    users.value.splice(index, 1)
  } else {
    if (!userMap.value.has(id)) {
      userMap.value.set(id, data!)
    }
    users.value.push(id)
  }
}
/* 搜索 */
/* 是否展示搜索栏 */
const showSearchBar = ref<boolean>(false)
const searchForm = ref<UserTable>({
  username: '',
  password: '',
  initTime: '',
  nickname: '',
  status: '',
  email: '',
  sex: '',
  phone: ''
})
// 页面加载
const loading = ref<boolean>(false)
let order = ''
// 获取页面数据
function getPageData() {
  loading.value = true
  getAllUser(page.value, searchForm.value, order)
    .then((tabs) => {
      page.value = tabs.data
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
}

// 排序
function onSort(e: Sort) {
  if (e.prop == 'initTime') {
    switch (e.order) {
      case 'ascending':
        order = 'asc'
        break
      case 'descending':
        order = 'desc'
        break
      default:
        order = e.order
    }
  }
  getPageData()
}
onMounted(() => {
  getFormatDictMap('sys_user_manage', 'head').then((d) => {
    tableDict.value = d
  })
  getFormatDictMap('sys_user_status', 'val').then((d) => {
    statusDict.value = d
  })
  getFormatDictMap('sys_user_sex', 'val').then((d) => {
    sexDict.value = d
  })
  getPageData()
  getGroupUsers()
})

// 重置搜索框
function reSearch() {
  searchForm.value = {
    username: '',
    password: '',
    initTime: '',
    nickname: '',
    status: '',
    email: '',
    sex: '',
    phone: ''
  }
  getPageData()
}

/* 选择器 */
const selectData = ref<UserTable[]>([])
function onSelect(data: UserTable[]) {
  selectData.value = data
}

// 保存更改
function save() {
  updateGroupUser(props.group, users.value)
    .then((d) => {
      ElMessage.success(d.msg)
    })
    .catch((d) => {
      ElMessage.error(d.msg)
    })
}

function test(d: any) {
  console.log(d)
}
</script>

<template>
  <el-row>
    <el-col :span="12">
      <div class="page-root">
        <div class="control">
          <div class="search" v-show="showSearchBar">
            <el-form :inline="true">
              <el-form-item :label="tableDict?.get('username') || 'username'">
                <el-input
                  v-model="searchForm.username"
                  :placeholder="'请输入' + tableDict?.get('username') || 'username'"
                ></el-input>
              </el-form-item>
              <el-form-item :label="tableDict?.get('nickname') || 'nickname'">
                <el-input
                  v-model="searchForm.nickname"
                  :placeholder="'请输入' + tableDict?.get('nickname') || 'nickname'"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="getPageData">搜索</el-button>
                <el-button :icon="Refresh" @click="reSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="ctl-bts">
            <span class="ctl-l"> </span>
            <span class="ctl-r">
              <el-button :icon="Search" circle @click="showSearchBar = !showSearchBar"></el-button>
              <el-button :icon="Refresh" @click="getPageData" circle></el-button>
            </span>
          </div>
        </div>
        <div class="ctx">
          <el-table
            v-loading="loading"
            @sort-change="onSort"
            table-layout="auto"
            :stripe="true"
            :data="page.rows"
            height="100%"
            :flexible="true"
            @selection-change="onSelect"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="username" align="center">
              <template #header>
                {{ tableDict?.get('username') || 'username' }}
              </template>
            </el-table-column>
            <el-table-column prop="nickname" align="center">
              <template #header>
                {{ tableDict?.get('nickname') || 'nickname' }}
              </template>
            </el-table-column>
            <el-table-column prop="head" align="center">
              <template #header>
                {{ tableDict?.get('head') || 'head' }}
              </template>
              <template #default="{ row }">
                <el-avatar :icon="(icon as any)[row.head!]" :src="UrlFormat(row.head)" />
              </template>
            </el-table-column>
            <el-table-column sortable="custom" prop="initTime" align="center">
              <template #header>
                {{ tableDict?.get('initTime') || 'initTime' }}
              </template>
              <template #="{ row }">
                {{ dateFormat(row['initTime']) }}
              </template>
            </el-table-column>
            <el-table-column prop="组状态" align="center">
              <template #="{ row }">
                <el-switch
                  :modelValue="users.includes(row.uId)"
                  @change="changeUser(row.uId, row)"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
          <Pagination :page="page" :get-page-data="getPageData" />
        </div>
      </div>
    </el-col>
    <el-col :span="12">
      <el-empty v-if="users.length == 0" description="无用户" />
      <el-card v-else shadow="hover">
        <el-tag
          class="user-tag"
          closable
          v-for="item in users"
          :key="item"
          @close="changeUser(item)"
        >
          <div class="user-tag-box">
            <span> 账号: </span>
            <span>
              {{ userMap.get(item)?.username }}
            </span>
            <el-avatar
              :icon="(icon as any)[userMap.get(item)?.head!]"
              :src="UrlFormat(userMap.get(item)?.head!)"
            />
          </div>
        </el-tag>
      </el-card>
    </el-col>
    <el-col :span="24" class="buttons">
      <el-button type="success" @click="save">保存</el-button>
    </el-col>
  </el-row>
</template>
<style scoped lang="less">
@import '../../../assets/page_bgl.less';
.user-tag {
  height: auto;
  margin: 5px;
  .user-tag-box {
    display: flex;
    align-items: center;
    padding: 5px 0;
  }
}
.buttons {
  text-align: center;
}
</style>
